﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GeoWeb.DataContext;
using GeoWeb.Common;

namespace GeoWeb.Demo.WorkDataConfig
{
    /// <summary>
    /// 工作日配置数据库操作类
    /// add by zhangyu
    /// 2013.02.04
    /// </summary>
    public class WorkDataConfigDal : GeoWeb.Demo.DataContext.DbUtity
    {
        #region 根据指定的年月获取该月的非工作日列表集合
        /// <summary>
        /// 根据指定的年月获取该月的非工作日列表集合
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public List<GeoWorkDay> GetListDateByYearAndMonth(int year, int month)
        {
            List<GeoWorkDay> list = Db.From<GeoWorkDay>()
                .Where(GeoWorkDay._.Day_year == year && GeoWorkDay._.Day_month == month && GeoWorkDay._.DaY_IsWorkDay == 1)
                .ToList<GeoWorkDay>() as List<GeoWorkDay>;
            return list;
        }
        #endregion

        #region 设置指定年月的日期的状态（工作日OR非工作日）
        /// <summary>
        /// 设置指定年月的日期的状态（工作日OR非工作日）
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="state"></param>
        /// <param name="Days"></param>
        /// <returns></returns>
        public bool SetDaysState(int year, int month, int state, int[] Days)
        {
            bool IsSuccess = false;

            DbTrans trans = Db.BeginTrans();//开始一个事务

            int temp_Rows = 0;//操作影响的行数

            temp_Rows = trans.Delete<GeoWorkDay>(GeoWorkDay._.Day_year == year && GeoWorkDay._.Day_month == month && GeoWorkDay._.Day_day.In(Days));

            bool Trans_IsSucces = true;

            foreach (int i in Days)
            {
                Field[] OrmFields = { 
                                GeoWorkDay._.Day_year, 
                                GeoWorkDay._.Day_month, 
                                GeoWorkDay._.Day_day, 
                                GeoWorkDay._.Day_Fulldate, 
                                GeoWorkDay._.DaY_IsWorkDay, 
                                GeoWorkDay._.AddDate 
                                    };

                object[] OrmValues = {
                                year,
                                month,
                                i,
                                new DateTime(year,month,i),
                                state,
                                DateTime.Now
                                     };
                temp_Rows = trans.Insert<GeoWorkDay>(OrmFields, OrmValues);

                if (temp_Rows == 0)
                {
                    trans.Rollback();
                    Trans_IsSucces = false;
                    break;
                }
            }
            if (Trans_IsSucces)
            {
                trans.Commit();
                IsSuccess = true;
            }
            trans.Close();
            return IsSuccess;
        }
        #endregion

        #region 初始化指定的月份（将该月份的所有的周六周日设为非工作日）
        /// <summary>
        /// 初始化指定的月份（将该月份的所有的周六周日设为非工作日）
        /// 若已初始化则直接返回true
        /// </summary>
        /// <param name="year">年</param>
        /// <param name="month">月</param>
        /// <returns></returns>
        public bool InitMonthByYear(int year, int month)
        {
            bool IsSuccess = false;
            //取得指定年月的一条记录
            GeoInitWorkDay entity = Db.From<GeoInitWorkDay>()
                .Where(GeoInitWorkDay._.Init_Year == year && GeoInitWorkDay._.Init_Month == month)
                .ToSingle<GeoInitWorkDay>() as GeoInitWorkDay;
            //判断是否已初始化
            if (entity == null || entity.Init_state == 0)
            {
                //开始一个事务
                DbTrans trans = Db.BeginTrans();
                //当前月起始日期
                DateTime MonthStartDay = new DateTime(year, month, 1);
                //当前月结束日期
                DateTime MonthEndDay = MonthStartDay.AddMonths(1).AddDays(-1);
                //定义周六周日日期集合字典
                Dictionary<int, string> DicWeek = new Dictionary<int, string>();
                string temp = string.Empty;
                DateTime temp_Dtime = DateTime.Now;
                //遍历取得所胡的周六周日
                for (int i = MonthStartDay.Day; i <= MonthEndDay.Day; i++)
                {
                    temp_Dtime = MonthStartDay.AddDays(i - 1);
                    temp = temp_Dtime.DayOfWeek.ToString().ToLower();
                    if (temp == "saturday" || temp == "sunday")
                    {
                        DicWeek.Add(i, temp);
                    }
                }
                int[] FreeDays = DicWeek.Keys.ToArray<int>();

                IsSuccess = SetDaysState(year, month, 1, FreeDays);

                if (!IsSuccess)
                {
                    trans.Rollback();
                }
                else
                {
                    if (entity == null)
                    {
                        entity = new GeoInitWorkDay();
                        entity.Init_FullDate = new DateTime(year, month, 1);
                        entity.Init_Year = year;
                        entity.Init_Month = month;
                        entity.Init_state = 1;
                        if (trans.Save<GeoInitWorkDay>(entity) > 0)
                        {
                            IsSuccess = true;
                        }
                    }
                    else
                    {
                        if (trans.Update<GeoInitWorkDay>(GeoInitWorkDay._.Init_state, 1, GeoInitWorkDay._.Init_ID == entity.Init_ID) > 0)
                        {
                            IsSuccess = true;
                        }
                    }
                }

                if (IsSuccess)
                {
                    trans.Commit();
                }
                else
                {
                    trans.Rollback();
                }
                trans.Close();
            }
            else
            {
                IsSuccess = true;
            }
            return IsSuccess;
        }
        #endregion

        #region 根据指定时间段获取非工作日数据集合
        /// <summary>
        /// 根据指定时间段获取非工作日数据集合
        /// </summary>
        /// <param name="StartDate"></param>
        /// <param name="EndDate"></param>
        /// <returns></returns>
        public List<GeoWorkDay> GetFreeDaysByDates(DateTime StartDate, DateTime EndDate)
        {
            List<GeoWorkDay> list = Db.From<GeoWorkDay>().Where(GeoWorkDay._.Day_Fulldate.Between(StartDate, EndDate)).ToList<GeoWorkDay>() as List<GeoWorkDay>;

            return list;
        }
        #endregion

        #region 获取指定时间段内的工作日总数及非工作日总数
        /// <summary>
        /// 获取指定时间段内的工作日总数及非工作日总数
        /// </summary>
        /// <param name="startDate">起始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>LIST[0]：工作日总数   LIST[1]：非工作日总数</returns>
        public List<int> GetWorkDayCount(DateTime startDate, DateTime endDate)
        {
            List<int> Result = new List<int>();
            //判断 结束日期是否比起始日期要大
            if (endDate.CompareTo(startDate) <= 0)
            {
                Result.Add(0);
                Result.Add(0);
            }
            else
            {
                //TimeSpan tempTime = endDate.Subtract(startDate);
                //对所有的月进行循环  然后将没有初始化的月份进行初始化
                for (DateTime dt = startDate; dt <= endDate; dt = dt.AddMonths(1))
                {
                    InitMonthByYear(dt.Year, dt.Month);
                }

                //获取指定时间段内的非工作日总数 
                int FreeDaysCount = Db.From<GeoWorkDay>().Select(GeoWorkDay._.ID.Count())
                    .Where(GeoWorkDay._.Day_Fulldate.Between(startDate, endDate) && GeoWorkDay._.DaY_IsWorkDay == 1)
                    .ToScalar<int>();
                //获取两时间段之间的总天数  算上当前天 要+1
                int DaysCount = endDate.Subtract(startDate).Days + 1;
                //填充工作日天数
                Result.Add(DaysCount - FreeDaysCount);
                //填充非工作日天数
                Result.Add(FreeDaysCount);
            }

            return Result;
        }
        #endregion
    }
}